'use client';

import React, { createContext, useState, useCallback, useMemo, ReactNode } from 'react';
import { getWeatherByTime, WeatherData } from '@/services/api';

interface WeatherContextType {
  getWeatherForTime: (time: Date) => Promise<WeatherData | null>;
  cache: Record<string, WeatherData | null>;
}

export const WeatherContext = createContext<WeatherContextType | undefined>(undefined);

export const WeatherProvider = ({ children }: { children: ReactNode }) => {
  const [cache, setCache] = useState<Record<string, WeatherData | null>>({});

  // 生成缓存 key（UTC 小时）
  const makeKey = (time: Date) => {
    const iso = time.toISOString();
    return iso.split(':')[0]; // "2021-05-02T08"
  };

  const getWeatherForTime = useCallback(async (time: Date) => {
    const key = makeKey(time);
    if (cache[key] !== undefined) {
      return cache[key];
    }
    const data = await getWeatherByTime(time.toISOString());
    setCache(prev => ({ ...prev, [key]: data }));
    return data;
  }, [cache]);

  const value = useMemo(() => ({ getWeatherForTime, cache }), [getWeatherForTime, cache]);

  return <WeatherContext.Provider value={value}>{children}</WeatherContext.Provider>;
};